import { createStore } from 'vuex'
import useStorage from "@/utils/useStorage";
import { http} from "@/api";
import {defaultMockMenu} from "@/utils/common";
const storage = useStorage()
function getMenuList(menu) {
    let list = JSON.parse(JSON.stringify(defaultMockMenu)).map(el => {
        console.log(el)
        if (el.children) {
            return {
                ...el,
                children: el.children.filter(el2 => {
                    return menu.includes(el2.code)
                })
            }
        } else {
            if (menu.includes(el.code)) {
                return {
                    ...el
                }
            }
        }
        return  null
    })
    return list.filter(el => el).filter(el => !el.children || el.children.length)
}

export default createStore({
  state: {
    token: storage.getItem('token') || '',
    userInfo: storage.getItem('userInfo') || {},
      menuList: storage.getItem('menuList') || '',
  },
  getters: {
    token: (state) => state.token,
    nickname: (state) => state.userInfo.nickname || '',
    userInfo: (state) => state.userInfo || {},
    menuList: (state) => state.menuList,
  },
  mutations: {
       setToken(state, token) {
            state.token = token
       },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo
        },
        setMenuList(state, menuList) {
             state.menuList = menuList
        },
  },
  actions: {
    login({ commit }, data) {
      return new Promise((resolve, reject) => {
        http.login(data).then(res => {
            const { token } = res.data
            let menuList = []
            if (res.data.role) {
                menuList = getMenuList((res.data.role.menu || '').split(','))
            } else {
                menuList = JSON.parse(JSON.stringify(defaultMockMenu))
            }
            storage.setItem('menuList', menuList)
            storage.setItem('token', token)
            storage.setItem('userInfo', res.data)
            commit('setToken', token)
            commit('setUserInfo', res.data)
            commit('setMenuList', menuList)
            resolve(res)
        }).catch(err => {
            reject(err)
        })
      })
    },
    resetState({ commit }) {
      return new Promise((resolve, reject) => {
        storage.removeItem('token')
        storage.removeItem('userInfo')
        storage.removeItem('menuList')

        commit('setToken', '')
        commit('setUserInfo', {})
        commit('setMenuList', [])
        resolve()
      })
    },
  },
  modules: {
  }
})
